<template>
  <div class="app-main-box" v-if="$route.path === '/transportOrderManagement/endShortBarge'">
    <!-- 导入数据 -->
    <!-- <div class="func-btn">
      <el-dropdown popper-class="dropDownStyle" :teleported="false" type="primary" style="margin-right: 12px;"
        @command="handleCommand">
        <el-button-group>
          <el-button type="primary">导入数据</el-button>
          <el-button type="primary" icon="ArrowDown" style="width: 32px;"></el-button>
        </el-button-group>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="multiply_important">批量导入</el-dropdown-item>
            <el-dropdown-item command="history_important">历史导入</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div> -->

    <!-- 搜索区域 -->
    <el-form class="global-search-form" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item class="from-item" label="磅单号：" prop="weightBillNo" style="width: 260px;">
        <el-input v-noSpace v-model="queryParams.weightBillNo" placeholder="请输入磅单号" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item class="from-item" label="箱号：" prop="containerNo">
        <el-input v-noSpace v-model="queryParams.containerNo" placeholder="请输入箱号" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item class="from-item" label="车牌号：" prop="plateNo">
        <el-input v-noSpace v-model="queryParams.plateNo" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item class="from-item" label="过磅日期：" style="min-width: max-content;width: 504px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" placement="right" :teleported="false"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button class="global-search-button" type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button class="global-search-button" icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
   <div class="global-table-container">
    <el-table class="global-border-radius-table" algin="center" v-loading="loading" :data="transportList">
      <el-table-column label="车牌号" prop="plateNo" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="箱号" prop="containerNo" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="磅单号" prop="weightBillNo" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="过磅日期" prop="weightingDate" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="货物名称" prop="cargo" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="净重(吨)" prop="netWeight" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column label="导入人" prop="creatorName" min-width="120" :show-overflow-tooltip="true" />
      <el-table-column label="导入时间" prop="createTime" min-width="200" :show-overflow-tooltip="true" />
      <!-- <el-table-column fixed="right" label="操作" class-name="small-padding" min-width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="openDialog(scope.row)">编辑</el-button>
        </template>
      </el-table-column> -->
    </el-table>
   </div>

    <!-- 导入文件对话框 -->
    <el-dialog :title="title" v-model="dialogVisiable" :width="680" append-to-body
      @close="dialogVisiable && handelClose()">
      <el-upload  class="upload-demo" drag accept=".csv, .xls, .xlsx"
        :on-change="handleChange" :auto-upload="false" :multiple="false">
        <!-- 未获取到文件列表(未上传) -->
        <div v-if="fileList.length == 0 && upload_status == ''" class="upload-content">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            <div class="el-upload-instructment">
              <span class="instructment-text">点击将文件拖拽到此处</span>
              <span class="suppose-type-text">支持格式.xlsx，.xls，csv，文件大小不得大于5M，最多支持导入2000条数据</span>
              <div class="download-template">
                <el-link type="primary" icon="Download" :underline="false" style="vertical-align: baseline;"
                  @click.stop.native="downloadTemplate">下载模板</el-link>
              </div>
            </div>
          </div>
        </div>

        <!-- 获取到文件列表(未上传) -->
        <div v-if="fileList.length && upload_status == ''" class="upload-content" @click="handleCapture" @dragover.stop
          v-loading="upload_loading" element-loading-text="正在导入...">
          <div class="file-icon"><span class="file-text">X</span></div>
          <div class="el-upload__text">
            <div class="el-upload-instructment">
              <div class="file-info">
                <span class="instructment-text file-name">{{ current_file.name }}</span>
                <span v-if="current_file.size / 1024 > 1024" class="file-size">（{{ (current_file.size / 1024 /
                  1024).toFixed(2) }}MB）</span>
                <span v-else class="file-size">（{{ (current_file.size / 1024).toFixed(2) }}KB）</span>
              </div>
              <span class="suppose-type-text">支持格式.xlsx，.xls，csv，文件大小不得大于5M，最多支持导入1000条数据</span>
              <el-button class="toggle-btn" type="default" plain @click.native>重新选择</el-button>
              <div class="download-template">
                <el-link type="primary" icon="Download" :underline="false" style="vertical-align: baseline;"
                  @click.stop.native="downloadTemplate">下载模板</el-link>
              </div>
            </div>
          </div>
        </div>

        <!-- 上传了成功状态 -->
        <div v-if="upload_status == 'success'" class="upload-content" @click.stop @dragover.stop>
          <el-icon :size="50" color="#00b42a">
            <CircleCheck />
          </el-icon>
          <div class="upload-success-text">导入成功，共导入{{ amount }}条数据</div>
        </div>

        <!-- 上传了失败状态 -->
        <div v-if="upload_status == 'fail'" class="upload-fail-content" @click.stop @dragover.stop>
          <div class="upload-fail-line">
            <el-icon :size="50" color="#ee0909">
              <CircleClose />
            </el-icon>
            <span class="upload-fail-text">导入出错</span>
          </div>
          <div class="upload-fail-instructment">表格中存在错误,具体错误如下,请检查后重新导入...</div>
          <div class="upload-fail-table">
            <div v-if="upload_error_message" class="infinite-list-wrapper">
              <ul class="list-message-container">
                <li class="list-message" v-html="upload_error_message">
                </li>
              </ul>
            </div>
            <div v-else class="infinite-list-wrapper">
              <ul class="list">
                <li v-for="i in errorList" :key="i.rowIndex" class="list-item">{{ `第${i.rowIndex}行，${i.errorMsg}` }}
                </li>
              </ul>
            </div>
          </div>

        </div>
      </el-upload>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="upload_status == '' && !fileList.length" type="info">
          导入
        </el-button>
        <el-button v-if="upload_status == '' && fileList.length" type="primary" @click="submitUpload"
          :="upload_loading ? true : false">
          导入
        </el-button>
        <el-button v-if="upload_status === 'fail'" type="primary" @click="uploadAgain">
          重新导入
        </el-button>
        <el-button v-if="upload_status === 'success'" type="primary" @click="uploadAgain">
          再次导入
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑到端短驳对话框 -->
    <el-dialog title="编辑运单" v-model="dialog_form_edit" width="800px" style="min-width: 750px" append-to-body>
      <!-- 编辑表单区域 -->
      <el-form class="global-form-edit" :model="formEdit" ref="formEditRef" :rules="formEditRules"
        label-width="120px">
        <el-form-item label="车牌号：" prop="plateNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.plateNo" class="form-input" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>
        <el-form-item label="箱号：" prop="containerNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.containerNo" class="form-input" placeholder="请输入箱号"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="磅单号：" prop="weightBillNo" class="form-items">
          <el-input v-noSpace v-model="formEdit.weightBillNo" class="form-input" placeholder="请输入磅单号"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="过磅日期：" prop="weightingDate" class="form-items">
          <el-date-picker value-format="YYYY-MM-DD" v-model="formEdit.weightingDate" type="date" placeholder="请选择过磅日期"
            style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="货物名称：" prop="cargo" class="form-items">
          <el-input v-noSpace v-model="formEdit.cargo" class="form-input" placeholder="请输入货物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="净重(吨)：" prop="netWeight" class="form-items">
          <el-input v-noSpace v-model="formEdit.netWeight" class="form-input" placeholder="请输入净重" clearable>
            <template #append>吨</template>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="dialog-footer" style="margin-top: 2px;">
        <el-button type="primary" @click="submitFormEdit">确 定</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 页码控件 -->
    <!-- <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
      v-model:limit="queryParams.pageSize" @pagination="getList" /> -->

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageIndex"
        v-model:limit="queryParams.pageSize" :pageSizes="[15, 20, 30, 50]" @pagination="getList" />
  </div>

  <router-view v-else></router-view>
</template>

<script setup name="transportOrderList">
import { ElMessage } from 'element-plus'
import { getListApi, importFileApi, updateListApi } from "@/api/transportOrderManagement/endShortBarge";
import { ref } from 'vue';
const router = useRouter();
const { proxy } = getCurrentInstance();
let historyRecord = ref(false)
let dialogVisiable = ref(false);  // 导入文件
let dialog_form_edit = ref(false); // 到端短驳编辑
let loading = ref(true);
let upload_loading = ref(false);
let amount = ref(0) // 上传了多少条数据
let upload_status = ref('') // 成功-sucess/失败-fail/默认值为空
let upload_error_message = ref('') // 导入出错原因
let total = ref(0);
let title = ref("");
let dateRange = ref([]);
let transportList = reactive([]) // 发端短驳
let errorList = reactive([])
let current_file = ref({})
let fileList = ref([])
let upload_status_record = reactive([])
/** 列表查询参数 */
const data = reactive({
  formEdit: {},
  formEditRules: {
    containerNo: [
      { required: true, message: "箱号不能为空", trigger: "blur" },
      // { max: 11, message: "箱号不能超过11位", trigger: "blur" }
    ],
    netWeight: [
      { required: true, message: "净重不能为空", trigger: "blur" },
      { pattern: /^(?!0(\.0+)?$)\d+(\.\d+)?$/, message: '仅允许输入大于0的小数和整数', trigger: 'blur' },
      { pattern: /^(?!0\d)(\d+(\.\d*)?|\.\d+)$/, message: '输入内容不合法', trigger: 'blur' },
    ],
    weightBillNo: [{ required: true, message: "磅单号不能为空", trigger: "blur" }],
    weightingDate: [{ required: true, message: "过磅日期不能为空", trigger: "blur" }],
    plateNo: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
    cargo: [{ required: true, message: "货物名称不能为空", trigger: "blur" }],
  },
  queryParams: {
    pageIndex: 1,
    pageSize: 15,
  }
});
const { queryParams, formEdit, formEditRules } = toRefs(data);
/** 
* Methods
*/

/** 导入指令事件 */
function handleCommand(command) {
  switch (command) {
    case 'multiply_important': importData(); break;
    case 'history_important': router.push('/transportOrderManagement/endShortBarge/historyRecord');
  }
}

/** 查询发端短驳 */
function getList() {
  loading.value = true;
  const params = queryParams.value
  getListApi(proxy.addDateRange(params, dateRange.value, 'Date')).then(response => {
    if (response.code === 1) {
      transportList = response.data.records;
      total.value = Number(response.data.total);
      loading.value = false;
    } else {
      loading.value = false;
    }
  }).catch(err => {
    loading.value = false;
  })
}

/** 导入请车数据 */
function importData() {
  reset()
  title.value = '导入数据'
  dialogVisiable.value = true
}

/** 下载导入模板 */
function downloadTemplate() {
  const link = document.createElement('a');
  link.href = 'https://bituo-logistics-saas.oss-cn-beijing.aliyuncs.com/web/excel/template/%E5%88%B0%E7%AB%AF%E6%95%B0%E6%8D%AE%E6%A8%A1%E6%9D%BF.xlsx'
  link.download = '到端数据模板.xlsx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 文件状态变化
function handleChange(file, fileList) {
  current_file.value = file.raw || file.file;
  // 获取最新的文件
  const latestFile = file.raw || file.file;
  // 将最新的文件加入到fileList中
  fileList.value = [latestFile];
}

/** 阻止默认行为 */
function handleCapture(event) {
  // 检查事件的目标是否为button
  if (event.target.innerText !== '重新选择') {
    event.stopPropagation();
  } else {
  }
}

/** 重新导入 */
function uploadAgain() {
  // 重置上传结果
  reset()
}

/** 上传接口 */
function submitUpload() {
  upload_loading.value = true
  let formData = new FormData();
  formData.append('file', current_file.value);
  importFileApi(formData).then(response => {
    if (response.code === 1) {
      upload_loading.value = false;
      amount.value = response.data
      upload_status.value = 'success'
    } else {
      upload_loading.value = false;
      upload_status.value = 'fail'
      upload_error_message.value = showErrorMsg(response.errorCode)
      errorList = response.data ? response.data : []
    }
    upload_status_record.push(upload_status.value)
  }).catch((err) => {
    upload_loading.value = false;
    upload_status.value = 'fail'
  })
}

/** 上传出错提示信息转换 */
function showErrorMsg(errorCode) {
  let message = ''
  switch (errorCode) {
    case 'DuplicateImport': message =
      ` <div>
          <p>您导入的Excel文件中存在以下问题：</p>
          <p>
            1. Excel文件中有重复的箱号和过磅日期组合。<br/>
            2. Excel文件中某些箱号和过磅日期组合在系统中已存在。
          </p>
          <p>请检查文件内容，确保没有重复的数据，并在修正后重新导入。如有疑问，请联系技术团队。</p>
        </div>
       `
      break;
    // case 'DuplicateImport': message = '请勿上传重复数据'; break;
    // case 'DuplicateImport': message = '请勿上传重复数据'; break;
    // case 'DuplicateImport': message = '请勿上传重复数据'; break;
    default: message = ''
  }
  return message
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageIndex = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 关闭弹窗 */
async function handelClose() {
  // 更新列表一定要在重置函数之前
  await updateListAfterUpload()
  upload_status_record = []
  reset();
}

/** 取消按钮 */
async function cancel() {
  dialogVisiable.value = false;
  // 更新列表一定要在重置函数之前
  await updateListAfterUpload()
  upload_status_record = []
  reset();
}

/** 关闭弹窗前判断是否需要更新列表数据 */
function updateListAfterUpload() {
  // 是否存在上传成功记录
  let isSuccess = upload_status_record.some(item => item === 'success')
  return new Promise((resolve, reject) => {
    if (isSuccess) {
      resetQuery()
    }
    resolve()
  })
}

/** 重置数据以及表单校验规则  */
function reset() {
  amount.value = 0
  errorList = []
  upload_error_message.value = ''
  upload_status.value = '' // 重置上传后的状态
  upload_loading.value = false;
  fileList.value = []
  current_file.value = {}
}

/** 打开编辑对话框 */
async function openDialog(row) {
  // 打开时重置表单
  resetEditForm()
  formEdit.value = { ...row }
  dialog_form_edit.value = true;
};

/** 提交表单 */
function submitFormEdit() {
  proxy.$refs["formEditRef"].validate(valid => {
    if (valid) {
      updateList()
    }
  })
}

/** 提交编辑铁路运单列表表单 */
function updateList() {
  let row = { ...formEdit.value, receiptDrayageId: formEdit.value.id }
  updateListApi(row).then(response => {
    if (response.code === 1) {
      updateTableRowData(response.data)
      dialog_form_edit.value = false
      ElMessage({ message: response.message || '操作成功', type: 'success' })
    } else {
      ElMessage({ message: response.message, type: 'error' })
    }
  }).catch(err => {
  })
}

/** 手动更新表格中某行的数据 */
function updateTableRowData(params) {
  transportList = transportList.map(item => {
    if (item.id.toString() == params.id.toString()) {
      item = Object.assign(item, params)
    }
    return item
  });
}

/** 编辑运单对话框-取消按钮 */
function cancelEdit() {
  dialog_form_edit.value = false;
  resetEditForm();
}

/** 重置编辑运单对话框 */
function resetEditForm() {
  formEdit.value = {
    weightBillNo: undefined,
    trainNo: undefined,
    containerNo: undefined,
    coverClothNo: undefined,
    waybillNo: undefined,
    cargo: undefined,
    weight: undefined,
    loadingDate: undefined,
    arrivalStation: undefined,
    departureStation: undefined,
    consignor: undefined,
    consignee: undefined
  }
  proxy.resetForm("formEditRef");
}

getList();
</script>

<style lang='scss' scoped>
@import '../../../assets/styles/variables.module.scss';

.app-main-box {
  background: #fff;
  border-radius: 12px;
  min-height: calc(100vh - 125px);
  width: calc(100% - 40px);

  /** 功能按钮 */
  .func-btn {
    padding: 24px 24px 0px;
  }
}

/** 导入说明文本 */
:deep(.el-upload__text) {
  width: 100%;
}

:deep(.el-upload-instructment) {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .file-info {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: nowrap;
    width: 24em;

    .file-name {
      font-size: 18px;
      display: inline-block;
      flex: 0 1 auto;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .file-size {
      font-size: 14px;
      align-self: flex-end;
      color: $--color-info;
      display: inline-block;
      flex: 0 1 auto;
    }
  }

  .instructment-text {
    font-size: 18px;
    color: #333;
    font-weight: bold;
  }

  .suppose-type-text {
    display: inline-block;
    font-size: 12px;
    color: $--color-info;
    margin-top: 10px;
  }

  .download-template {
    span {
      font-size: 14px;
      color: $--color-primary;
      display: inline-block !important;
      padding: 10px;
    }
  }
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 0px !important;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: transparent !important;
  border: none !important;
  border-radius: 0px !important;
}

:deep(.el-icon--upload) {
  margin-bottom: 0px !important;
}

/** 上传区域样式 */
.upload-content {
  border: 1px dashed $--color-info;
  background-color: $--color-bg-info !important;
  box-sizing: border-box !important;
  width: 100%;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 6px !important;
}

/** 上传失败区域 */
.upload-fail-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .upload-fail-line {
    display: flex;
    align-items: center;

    .upload-fail-text {
      font-size: 20px;
      color: #333;
      font-weight: bold;
      margin-left: 14px;
    }
  }

  .upload-fail-instructment {
    color: $--color-info;
    margin-top: 14px;
  }

  .upload-fail-table {
    width: 100%;
    height: 240px;
    margin-top: 20px;

    .infinite-list-wrapper {
      width: 100%;
      height: 100%;
      border-radius: 6px;
      background-color: $--color-bg-info;
      padding: 0px 20px;
      overflow-y: auto;
    }

    .list {
      padding: 0;
      margin: 0;
      list-style: none;

      .list-item {
        display: flex;
        align-items: flex-end;
        height: 30px;
        line-height: 1;
        color: $--color-danger;
        white-space: nowrap;
      }
    }

    .list-message-container {
      padding: 0;
      margin: 0;
      list-style: none;

      .list-message {
        text-align: left;
        color: $--color-danger;
      }
    }

  }
}

/** 隐藏上传的文本列表 */
:deep(.el-upload-list) {
  display: none;
}

/** 重新选择按钮 */
.toggle-btn {
  display: inline-block;
  margin-top: 14px;
}


/** 文件图标 */
.file-icon {
  width: 50px;
  height: 50px;
  background-color: #00b42a; // 与字体主题色success一致
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 14px;

  .file-text {
    display: inline-block;
    width: 50px;
    height: 50px;
    color: #fff;
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    line-height: 50px;
    transform: skew(-20deg);
  }
}

.upload-success-text {
  margin-top: 20px;
}


/** 编辑表单区域 */
.form {
  display: flex;
  flex-wrap: wrap;

  .form-items {
    width: calc(50% - 10px);
    align-items: center !important;

    .form-input {
      height: 36px !important;
      width: 100%;
    }
  }

  // .el-form-item--default {
  //   margin-bottom: 22px !important;
  // }
}

:deep(.el-form-item__label) {
  height: 36px;
  text-align: center !important;
  line-height: 36px !important;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

// 自定义下拉菜单样式
:deep(.dropDownStyle) {
  width: 120px !important;
  position: absolute !important;
  left: 0px !important;
  font-size: 14px;
  font-style: normal;

  .el-dropdown-menu__item {
    width: 100%;
    justify-content: center;
  }
}

// .custom-button {
//   background-color: transparent;
//   color: $--color-primary;
// }

// .custom-button:hover {
//   background-color: $--color-primary;
//   color: #fff;
// }</style>